<script setup>
import { showToast } from 'vant'
import { ref } from 'vue'
import { getUserClockStatusApi, exchangePrizeApi } from '@/apis/user'

let glist = ref([
  {
    id: 'g1',
    prizeid: 2,
    name: '',
    img: '',
    status: false,
    isshow: false
  },
  {
    id: 'g2',
    prizeid: 3,
    name: '',
    img: '',
    status: false,
    isshow: false
  }
])

// 接口-获取状态信息
const getUserStatus = async () => {
  const res = await getUserClockStatusApi()
  if (res.data.code !== 200) {
    return showToast(res.data.msg)
  }
  let data = res.data.data
  // console.log(data)
  // 奖品1
  if (data.prize1 != 0) {
    if (data.prize1 == 1) {
      glist.value[0].prizeid = 1
      glist.value[0].name = '定制笔记本'
      glist.value[0].img = new URL('../assets/img/g1.png', import.meta.url)
    } else {
      glist.value[0].prizeid = 2
      glist.value[0].name = '定制小熊猫玩具'
      glist.value[0].img = new URL('../assets/img/g2.png', import.meta.url)
    }
    glist.value[0].isshow = true
    data.exchange1 == 1 ? (glist.value[0].status = true) : (glist.value[0].status = false)
  } else {
    glist.value[0].isshow = false
  }

  // 奖品2
  if (data.prize2 != 0) {
    glist.value[1].prizeid = 3
    glist.value[1].name = '定制镭射包'
    glist.value[1].img = new URL('../assets/img/g3.png', import.meta.url)
    glist.value[1].isshow = true
    data.exchange2 == 1 ? (glist.value[1].status = true) : (glist.value[1].status = false)
  } else {
    glist.value[1].isshow = false
  }
}

getUserStatus()

const audioRef = ref(null)

function playAudio() {
  if (audioRef.value) {
    audioRef.value.play().catch((error) => {
      console.error('Error playing audio:', error)
    })
  }
}

let dhshow = ref(false)
let hxmsg = ref('请工作人员盖章核销')
let gid = ref('') //兑换商品id

// 接口-兑奖
const exchangePrize = async () => {
  let pid = ref('')
  if (gid.value == 'g1') {
    pid.value = glist.value[0].prizeid
  } else {
    pid.value = glist.value[1].prizeid
  }
  // 调用接口
  const res = await exchangePrizeApi({
    exchangeIndex: gid.value == 'g1' ? '1' : '2',
    prize: pid.value
  })
  if (res.data.code !== 200) {
    return showToast(res.data.msg)
  }
  // 播放盖章成功音效
  playAudio()
  // 更新奖品状态
  getUserStatus()
  // 更新盖章页文字
  hxmsg.value = '兑换成功'
  let timer = setTimeout(() => {
    // 关闭盖章页
    esp.closeStampCertifcationPage()
    document.getElementById('closeGzPage').remove()
    // document.getElementById('testbtn').remove()
    dhshow.value = false
    clearTimeout(timer)
  }, 2000)
}

// 拉起失败回调
const showFailed = () => {}

// 点击开启兑换
const openExchange = (id, status) => {
  if (status) {
    showToast('该奖品已兑换')
    return
  }
  gid.value = id
  dhshow.value = true
  hxmsg.value = '请工作人员盖章核销'
  // 拉起盖章页面
  esp.showStampCertifcationPage(
    {
      licenseId: 'L29578574823', //联系管理员获取（必填）
      merchantCode: 'A29474683191', //联系管理员获取（必填）
      regionCode: esp.REGION_CODE_TYPE.CHINA,
      languageCode: esp.LANGUAGE_CODE_TYPE.CHINESE
    },
    showFailed
  )
  // 影藏盖章页面关闭按钮
  document.getElementById('maopai-stamp-close-btn').style.display = 'none'

  // 动态添加关闭按钮
  let btn = document.createElement('img')
  btn.src = new URL('../assets/img/btn_back.png', import.meta.url)
  btn.id = 'closeGzPage'
  btn.style.position = 'fixed'
  btn.style.left = 'calc(50% - 1.34rem)'
  btn.style.bottom = '3rem'
  btn.style.width = '2.68rem'
  btn.style.zIndex = '1002'
  document.body.appendChild(btn)
  // 影藏盖章页面关闭按钮
  document.getElementById('maopai-stamp-close-btn').style.display = 'none'
  btn.onclick = () => {
    btn.remove()
    // document.getElementById('testbtn').remove()
    esp.closeStampCertifcationPage()
    dhshow.value = false
  }

  // 虚拟盖章按钮
  let tbtn = document.createElement('img')
  tbtn.src = new URL('../assets/img/btn_test.png', import.meta.url)
  tbtn.id = 'testbtn'
  tbtn.style.position = 'fixed'
  tbtn.style.opacity = '0'
  tbtn.style.right = '0'
  tbtn.style.top = '0'
  tbtn.style.width = '3.5rem'
  tbtn.style.zIndex = '1002'
  document.body.appendChild(tbtn)

  let cnum = ref(0)
  let ctimer = null
  tbtn.addEventListener('click', () => {
    cnum.value++
    // console.log(cnum.value)
    if (ctimer == null) {
      // 连续点击6次 打卡成功
      ctimer = setTimeout(() => {
        if (cnum.value >= 6) {
          // 盖章成功
          exchangePrize()
        }
        cnum.value = 0
        clearTimeout(ctimer)
        ctimer = null
      }, 3000)
    }
  })
}

//设置盖章认证失败回调
esp.certError(function cb(data) {
  //   alert('接受到认证失败回调:' + data.resMsg)
  showToast(data.resMsg)
})

// 不显示输入密码icon
esp.setNotShowOptIcon()

//设置盖章认证成功回调
esp.certSuccess(function cb(data) {
  // alert('接受到认证成功,该印章Id: [' + data.result.stamp + '] .')
  if (data.result.stamp !== '8963187583') {
    return showToast('请使用正确的印章')
  }
  exchangePrize()
})

//设置盖章页背景颜色（red, green, blue, opecity）
esp.setBackgroundColor(0, 0, 0, 0)

//设置盖章页文字 (传空则不显示)
esp.setDescription('')

//设置是否展示盖章动画
esp.setIconYn(false)
</script>
<template>
  <!-- 盖章成功音效 -->
  <audio controls="controls" ref="audioRef" preload hidden>
    <source src="../assets/media/stamp.mp3" type="audio/mp3" />
  </audio>
  <div class="exchange box bg clmcenter">
    <img src="@/assets/img/slogan.png" class="logo" />
    <p class="extitle">
      感谢您的参与<br />
      请至工作人员处领取奖品
    </p>
    <div class="giftbox">
      <p class="gtitle">您的奖品为</p>
      <div class="ginfo">
        <div
          class="gitem"
          v-for="item in glist"
          :key="item.id"
          @click="openExchange(item.id, item.status)"
          v-show="item.isshow"
        >
          <img :src="item.img" class="gimg" />
          <p class="gname">{{ item.name }}</p>
          <p class="gstatus">（{{ item.status ? '已兑换' : '待兑换' }}）</p>
        </div>
      </div>
    </div>
    <img
      src="@/assets/img/btn_back.png"
      class="btn btn_back btnani"
      @click="$router.replace('/map')"
    />
    <div class="gzbox clmcenter" v-show="dhshow">
      <img src="@/assets/img/slogan.png" class="logo" />
      <div class="gzinfo clmcenter">
        <div class="gzwrap clmcenter">
          <img src="@/assets/img/m5.png" class="tipsimg btnani" />
          <p class="tipstext">{{ hxmsg }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.logo {
  position: absolute;
  top: 70px;
  width: 230px;
}
.exchange {
  .extitle {
    font-size: 54px;
    text-align: center;
    margin-top: 50px;
  }
  .giftbox {
    margin-top: 150px;
    text-align: center;
    .gtitle {
      font-size: 46px;
    }
    .ginfo {
      margin-top: 20px;
      display: flex;
      .gitem {
        width: 200px;
        .gimg {
          width: 200px;
          height: 200px;
          border: 1px solid #ffffff;
          border-radius: 10px;
        }
        p {
          font-size: 28px;
          word-break: break-all;
          white-space: nowrap;
        }
        .gname {
          padding-top: 15px;
        }
      }
      .gitem:last-child {
        margin-left: 80px;
      }
    }
  }
  .btn_back {
    margin-top: 150px;
  }
}
.gzbox {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.8);
  z-index: 999;
  .gzinfo {
    width: 648px;
    height: 648px;
    background: url('@/assets/img/kuang.png') no-repeat;
    background-size: 100% 100%;
    margin-bottom: 150px;
    .gzwrap {
      width: 586px;
      height: 586px;
      background: rgba($color: #000000, $alpha: 0.8);
      .tipsimg {
        width: 200px;
        height: 200px;
        border-radius: 50%;
        box-shadow: 0 0 15px #fff;
        margin-top: 40px;
      }
      .tipstext {
        font-size: 40px;
        padding-top: 40px;
      }
    }
  }
}
</style>
